﻿using DGSFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.SessionState;

namespace Framework.Resources
{
    /// <summary>
    /// Summary description for ManagerFavorite
    /// </summary>
    public class ManagerFavorite : IHttpHandler, IReadOnlySessionState
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
            var userMember = Membership.GetUser();
            var roles = Roles.GetRolesForUser();
            var type = string.Empty;
            var status = 0;
            udv_Users user = null;
            if (context.User.Identity.IsAuthenticated)
            {
                var userID = new Guid(userMember.ProviderUserKey.ToString());
                user = entity.udv_Users.Where(d => d.UserID == userID).FirstOrDefault();
            }
            if (context.Request["type"] != null)
                type = context.Request["type"].ToString();
            if (type == "add")
            {
                var favName = HttpContext.Current.Request.Form["favName"].ToString();
                var userDb = entity.udv_Users.Where(d => d.UserID == user.UserID).FirstOrDefault();
                var favorite = new dgs_Favorite();
                favorite.udv_Users = userDb;
                favorite.FavName = favName;
                entity.AddTodgs_Favorite(favorite);
                var result = entity.SaveChanges() > 0;
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = 1,
                        FavID = favorite.FavID
                    })
                );

            }
            else if (type == "addbuy") //them vao danh sach mua
            {
                if (context.Request["stock"] != null && (userMember.UserName.Equals("MasterDK") || user.UserName.Equals("uyenadmin"))) //chua bo sung kiem qua quyen admin
                {
                    var stockCode = context.Request["stock"].ToString();
                    stockCode = stockCode.ToLower();
                    var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                    if (stock != null)
                    {
                        if (stock.IsWatchListBuy.Value)
                            status = -1;//da co trong danh sach buy
                        else
                        {
                            stock.IsWatchListBuy = true;
                            if (entity.SaveChanges() > 0)
                                status = 1;// them vao danh sach buy thanh cong
                        }
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                        new
                        {
                            Status = status
                        })
                );

            }
            else if (type == "deletebuy") //xoa stock khoi danh sach buy
            {
                if (context.Request["stock"] != null && (userMember.UserName.Equals("MasterDK") || user.UserName.Equals("uyenadmin"))) //chua bo sung kiem qua quyen admin
                {
                    var stockCode = context.Request["stock"].ToString();
                    stockCode = stockCode.ToLower();
                    var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                    if (stock != null)
                    {
                        if (stock.IsWatchListBuy.Value)
                        {
                            stock.IsWatchListBuy = false;
                            if (entity.SaveChanges() > 0)
                                status = 1;// xoa khoi danh sach thanh cong
                        }
                        else
                            status = -1;
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                        new
                        {
                            Status = status
                        })
                );
            }
            else if (type == "deletesell") //xoa stock khoi danh sach sell
            {
                if (context.Request["stock"] != null && (userMember.UserName.Equals("MasterDK") || user.UserName.Equals("uyenadmin"))) //chua bo sung kiem qua quyen admin
                {
                    var stockCode = context.Request["stock"].ToString();
                    stockCode = stockCode.ToLower();
                    var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                    if (stock != null)
                    {
                        if (stock.IsWatchListSell.Value)
                        {
                            stock.IsWatchListSell = false;
                            if (entity.SaveChanges() > 0)
                                status = 1;// xoa khoi danh sach thanh cong
                        }
                        else
                            status = -1;
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                        new
                        {
                            Status = status
                        })
                );
            }
            else if (type == "addsell") //them vao danh sach ban
            {
                if (context.Request["stock"] != null&&(userMember.UserName.Equals("MasterDK") || user.UserName.Equals("uyenadmin"))) //chua bo sung kiem qua quyen admin
                {
                    var stockCode = context.Request["stock"].ToString();
                    stockCode = stockCode.ToLower();
                    var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                    if (stock != null)
                    {
                        if (stock.IsWatchListSell.Value)
                            status = -1;//da co trong danh sach buy
                        else
                        {
                            stock.IsWatchListSell = true;
                            if (entity.SaveChanges() > 0)
                                status = 1;// them vao danh sach buy thanh cong
                        }
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                        new
                        {
                            Status = status
                        })
                );

            }
            else if (type == "delete")
            {
                if (context.Request["favID"] != null)
                {
                    var favID = int.Parse(context.Request["favID"].ToString());
                    if (userMember.UserName.Equals("MasterDK") || userMember.UserName.Equals("uyenadmin"))
                    {
                        var fav = entity.dgs_Favorite.Where(d => d.FavID == favID).FirstOrDefault();
                        if (fav != null)
                        {
                            entity.DeleteObject(fav);
                            entity.SaveChanges();
                            status = 1;
                        }
                    }
                    else
                    {
                        var fav = entity.dgs_Favorite.Where(d => d.FavID == favID && d.udv_Users.UserID == user.UserID).FirstOrDefault();
                        if (fav != null)
                        {
                            entity.DeleteObject(fav);
                            entity.SaveChanges();
                            status = 1;
                        }
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = status
                    })
                );

            }
            else if (type == "deletestock")
            {
                if (context.Request["stock"] != null && (userMember.UserName.Equals("MasterDK") || user.UserName.Equals("uyenadmin")))
                {
                    var stockCode = context.Request["stock"].ToString();
                    var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                    if (stock != null)
                    {
                        stock.IsDelete = true;
                        stock.UpdateDate = DateTime.Now;
                        if (user != null)
                            stock.UpdateBy = user.UserName;
                        if (entity.SaveChanges() > 0)
                            status = 1;
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = status
                    })
                );
            }
            else if (type == "getcontext")
            {
                var data = string.Empty;
                var dataMenu = string.Empty;
                if (context.Request["typeStock"] != null)
                {
                    var typeStock = context.Request["typeStock"].ToString().ToLower();
                    List<dgs_Favorite> favList = null;
                    if (user.UserName.Equals("MasterDK"))
                    {
                        var memAdmin = Membership.GetUser("uyenadmin");
                        var userIDAdmin = new Guid(memAdmin.ProviderUserKey.ToString());
                        favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID || d.udv_Users.UserID == userIDAdmin).ToList();
                    }
                    else if (user.UserName.Equals("uyenadmin"))
                    {
                        var memAdmin = Membership.GetUser("MasterDK");
                        var userIDAdmin = new Guid(memAdmin.ProviderUserKey.ToString());
                        favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID || d.udv_Users.UserID == userIDAdmin).ToList();
                    }
                    else
                        favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID).ToList();


                    dataMenu = Globals.GetDropdownMenu(userMember.UserName, roles, favList);
                    data = Globals.GetMenuContext(userMember.UserName, typeStock, roles, favList);
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Data = data,
                        DataMenu = dataMenu
                    })
                );
            }
            else if (type == "list")
            {
                List<dgs_Favorite> favList = null;
                if (user.UserName.Equals("MasterDK"))
                {
                    var memAdmin = Membership.GetUser("uyenadmin");
                    var userIDAdmin = new Guid(memAdmin.ProviderUserKey.ToString());
                    favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID || d.udv_Users.UserID == userIDAdmin).ToList();
                }
                else if (user.UserName.Equals("uyenadmin"))
                {
                    var memAdmin = Membership.GetUser("MasterDK");
                    var userIDAdmin = new Guid(memAdmin.ProviderUserKey.ToString());
                    favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID || d.udv_Users.UserID == userIDAdmin).ToList();
                }
                else
                    favList = entity.dgs_Favorite.Where(d => d.udv_Users.UserID == user.UserID).ToList();
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Data = favList.Select(d => new
                        {
                            d.FavID,
                            d.FavName,
                            d.FavName_en
                        }).ToList()
                    })
                );
            }
            else if (type == "add2fav")
            {
                if (context.Request["stock"] != null && context.Request["favID"] != null)
                {
                    var favID = int.Parse(context.Request["favID"].ToString());
                    var stockCode = context.Request["stock"].ToString();
                    //kiem tra stock da co trong danh sach chua, neu co roi thi bao loi
                    var favDetailsExist = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favID).FirstOrDefault();
                    if (favDetailsExist != null)
                    {
                        status = -1; //da ton tai
                    }
                    else
                    {
                        if (userMember.UserName.Equals("MasterDK") || userMember.UserName.Equals("uyenadmin"))
                        {
                            var fav = entity.dgs_Favorite.Where(d => d.FavID == favID).FirstOrDefault();
                            if (fav != null)
                            {
                                var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                                if (stock != null)
                                {
                                    var favDetails = new dgs_FavoriteDetails();
                                    favDetails.dgs_Favorite = fav;
                                    favDetails.dgs_Stocks = stock;
                                    favDetails.StockCode = stockCode;
                                    favDetails.DateCreate = DateTime.Now;
                                    entity.AddTodgs_FavoriteDetails(favDetails);
                                    if (entity.SaveChanges() > 0)
                                        status = 1;
                                }
                            }
                            else
                                status = -2; //loi
                        }
                        else
                        {
                            var fav = entity.dgs_Favorite.Where(d => d.FavID == favID&&d.udv_Users.UserID==user.UserID).FirstOrDefault();
                            if (fav != null)
                            {
                                var stock = entity.dgs_Stocks.Where(d => d.Code == stockCode).FirstOrDefault();
                                if (stock != null)
                                {
                                    var favDetails = new dgs_FavoriteDetails();
                                    favDetails.dgs_Favorite = fav;
                                    favDetails.dgs_Stocks = stock;
                                    favDetails.StockCode = stockCode;
                                    favDetails.DateCreate = DateTime.Now;
                                    entity.AddTodgs_FavoriteDetails(favDetails);
                                    if (entity.SaveChanges() > 0)
                                        status = 1;
                                }
                            }
                            else
                                status = -2; //loi
                        }
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = status
                    })
                );
            }
            else if (type == "deletefavitem")
            {
                if (context.Request["stock"] != null && context.Request["favID"] != null)
                {                    
                    var favID = int.Parse((context.Request["favID"].ToString().Split('_'))[1]);
                    var stockCode = context.Request["stock"].ToString();
                    if (userMember.UserName.Equals("uyenadmin") || userMember.UserName.Equals("MasterDK"))
                    {
                        var favItem = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favID).FirstOrDefault();
                        if (favItem != null)
                        {
                            entity.DeleteObject(favItem);
                            if (entity.SaveChanges() > 0)
                                status = 1;
                        }
                    }
                    else
                    {
                        var favItem = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favID&&d.dgs_Favorite.udv_Users.UserID==user.UserID).FirstOrDefault();
                        if (favItem != null)
                        {
                            entity.DeleteObject(favItem);
                            if (entity.SaveChanges() > 0)
                                status = 1;
                        }
                    }

                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = status
                    })
                );
            }
            else if (type == "movefavitem")
            {
                if (context.Request["stock"] != null && context.Request["favIDFrom"] != null && context.Request["favIDTo"] != null)
                {
                    var favIDFrom = int.Parse((context.Request["favIDFrom"].ToString().Split('_'))[1]);
                    var favIDTo = int.Parse(context.Request["favIDTo"].ToString());
                    var stockCode = context.Request["stock"].ToString();
                    //kiem tra stock da co trong danh sach fav den chua, neu chua thi them vao, co roi thi thong bao loi
                    var favItemTo = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favIDTo).FirstOrDefault();
                    if (favItemTo != null) //da ci trong danh sach den
                    {
                        status = -1;
                    }
                    else
                    {
                        if (userMember.Equals("MasterDK") || userMember.Equals("uyenadmin"))
                        {
                            var favItem = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favIDFrom).FirstOrDefault();
                            if (favItem != null)
                            {
                                var favTo = entity.dgs_Favorite.Where(d => d.FavID == favIDTo).FirstOrDefault();
                                if (favTo != null)
                                {
                                    favItem.dgs_Favorite = favTo;
                                    if (entity.SaveChanges() > 0)
                                        status = 1;
                                }
                            }
                        }
                        else
                        {
                            var favItem = entity.dgs_FavoriteDetails.Where(d => d.StockCode == stockCode && d.dgs_Favorite.FavID == favIDFrom&&d.dgs_Favorite.udv_Users.UserID==user.UserID).FirstOrDefault();
                            if (favItem != null)
                            {
                                var favTo = entity.dgs_Favorite.Where(d => d.FavID == favIDTo&&d.udv_Users.UserID==user.UserID).FirstOrDefault();
                                if (favTo != null)
                                {
                                    favItem.dgs_Favorite = favTo;
                                    if (entity.SaveChanges() > 0)
                                        status = 1;
                                }
                            }
                        }
                    }
                }
                context.Response.Write(
                    jsonSerializer.Serialize(
                    new
                    {
                        Status = status
                    })
                );
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}